package com.xuecheng.content.service.jobhandler;

import com.xuecheng.base.exception.StudySystemException;
import com.xuecheng.content.feignclient.SearchServiceFeignClient;
import com.xuecheng.content.mapper.CoursePublishMapper;
import com.xuecheng.content.model.po.CoursePublish;
import com.xuecheng.content.service.BuilderHtmlPageService;
import com.xuecheng.content.service.CoursePublishService;
import com.xuecheng.messagesdk.model.po.MqMessage;
import com.xuecheng.messagesdk.service.MessageProcessAbstract;
import com.xuecheng.messagesdk.service.MqMessageService;
import com.xuecheng.search.po.CourseIndex;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.util.Objects;

/**
 * @author Tang
 * @version 1.0
 * @date 2024/1/8 17:43
 */
@Slf4j
@Component
public class CoursePublishTask extends MessageProcessAbstract {
    private final static String HTML_PAGE_PATH = "/Users/tang/code/study-system/study-content/content-service/src/main/resources/builderHtml/";
    public final static String HTML_PAGE_FILE_NAME = "%s.html";
    private final static String HTML_TEMPLATE_PATH = "/templates/";
    private final static String HTML_TEMPLATE_FILE_NAME = "course_template.ftl";
    private final static String UPLOAD_HTML_PATH = "/course";
    private final SearchServiceFeignClient searchServiceFeignClient;
    private final BuilderHtmlPageService builderHtmlPageService;
    private final CoursePublishMapper coursePublishMapper;
    public CoursePublishTask(BuilderHtmlPageService builderHtmlPageService,
                             SearchServiceFeignClient searchServiceFeignClient,
                             CoursePublishMapper coursePublishMapper) {
        this.builderHtmlPageService = builderHtmlPageService;
        this.searchServiceFeignClient = searchServiceFeignClient;
        this.coursePublishMapper = coursePublishMapper;
    }

    @XxlJob("CoursePublishJobHandler")
    public void publish() throws Exception {
        int shardTotal = XxlJobHelper.getShardTotal();
        int shardIndex = XxlJobHelper.getShardIndex();
        this.process(shardIndex,
                shardTotal,
                "course_publish",
                30,
                60);
    }

    @Override
    public boolean execute(MqMessage mqMessage) throws Exception {
        Long courseId = Long.valueOf(mqMessage.getBusinessKey1());
        // 生成html页面
        builderStaticHtmlPages(mqMessage, courseId);
        // 构建es索引
        builderEsIndex(mqMessage, courseId);
        // 构建redis缓存
        builderRedisCache(mqMessage, courseId);
        // 返回true表示任务完成
        return true;
    }

    private void builderRedisCache(MqMessage mqMessage, Long courseId) {
        MqMessageService mqMessageService = this.getMqMessageService();
        int mq = mqMessageService.getStageThree(mqMessage.getId());
        if (mq > 0) {
            log.info("已构建redis缓存，无需再处理");
            return;
        }
        mqMessageService.completedStageThree(mqMessage.getId());
    }

    public void builderStaticHtmlPages(MqMessage mqMessage, Long courseId) throws IOException, TemplateException {
        MqMessageService mqMessageService = this.getMqMessageService();
        int mq = mqMessageService.getStageOne(mqMessage.getId());
        if (mq > 0) {
            log.info("生成静态html页面完成，无需再处理");
            return;
        }
        // 生成静态页面
        File htmlPageFile = builderHtmlPageService.builderHtmlPageFile(HTML_TEMPLATE_PATH, HTML_TEMPLATE_FILE_NAME,
                HTML_PAGE_PATH,
                String.format(HTML_PAGE_FILE_NAME, courseId),
                courseId);
        if (Objects.isNull(htmlPageFile)) {
            log.error("生成的html页面异常");
        }
        builderHtmlPageService.uploadHtmlPage(htmlPageFile, UPLOAD_HTML_PATH,
                String.format(HTML_PAGE_FILE_NAME, courseId));
        htmlPageFile.delete();
        mqMessageService.completedStageOne(mqMessage.getId());
    }

    public void builderEsIndex(MqMessage mqMessage, Long courseId) {
        MqMessageService mqMessageService = this.getMqMessageService();
        int stageTwo = mqMessageService.getStageTwo(mqMessage.getId());
        if (stageTwo > 0) {
            log.info("课程es已经构建索引，无需重复构建");
            return;
        }
        CoursePublish coursePublish = coursePublishMapper.selectById(courseId);
        CourseIndex courseIndex = new CourseIndex();
        BeanUtils.copyProperties(coursePublish, courseIndex);
        coursePublish = null;
        // 远程调用来构建es索引
        Boolean isSuccess = searchServiceFeignClient.add(courseIndex);
        if (!isSuccess) {
            StudySystemException.cast("远程调用搜索服务，添加课程索引添加失败");
        }
        mqMessageService.completedStageTwo(mqMessage.getId());
    }

}
